// pages/user/user.js

import API from "../../data/api";
import Util from "../../utils/util";

const App = getApp();
const Config = App.Config;

Page({
  data: {
    Stnumber: null,
    Stpassword: null,
    StInfo: null,
    selectUserInfo: false, // 显示个人信息
    spreakingAnimation: {}, // 放大动画  
    userInfo: {}, // 用户信息
    openId: null, // openId
    HOSTIMG: Config.HOSTIMG,
    windowWidth: App.globalData.systemInfo.windowWidth,
    windowHeight: App.globalData.systemInfo.windowHeight
  },
  onShow: function (options) {

    var that = this

    that.setData({
      userInfo: App.globalData.userInfo,
      openId: App.globalData.openId
    })

    if (App.globalData.openId == '' || App.globalData.openId == null) {
      Util.UI.loading(1000, '授权失败,请退出小程序重新登录');
      setTimeout(function () {
        wx.switchTab({
          url: '../index/index',
        })
      }, 1000)
    } else {

      App.Util.getStNumberPassword(App.globalData.openId) // 获取学号密码
        .then((res) => {
          // console.log(res.data.number);
          return App.Util.checkBind(res);
        })
        .then((res) => {
          // console.log(res);
          that.setData({
            Stnumber: res.data.number,
            Stpassword: res.data.password,
          });
        })
    }

  },

  // 折叠个人信息
  foldUserInfo: function () {
    var that = this;

    // 没有数据才去请求数据
    if (that.data.StInfo == null || that.data.StInfo == "") {
      that.getStInfo();
    }
    that.setData({
      selectUserInfo: !that.data.selectUserInfo,
      spreakingAnimation: {}
    });
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out',
    })
    animation.opacity(1).translateY(5).step()
    this.setData({
      spreakingAnimation: animation.export()
    })
  },

  // 获取个人信息
  getStInfo: function () {
    var that = this;
    API.getStInfo(that.data.Stnumber, that.data.Stpassword)
      .then((res) => {
        // console.log(res);
        if (res.data.error == Config.ERR.OK) {
          that.setData({ StInfo: res.data.data });
        } else if (res.data.error == Config.ERR.ER) {
          Util.UI.loading(1000, res.data.data);
        }
      });
  },

  // 解绑
  unbind: function () {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '北鼻,确定解绑吗？',
      success: function (res) {
        if (res.confirm) {
          that.actionUnBind();
        }
      }
    });


  },

  // 执行解绑
  actionUnBind: function () {
    var that = this;
    API.unbind(App.globalData.openId)
      .then((res) => {
        // console.log(res);
        if (res.data.error == Config.ERR.OK) {
          that.setData({ StInfo: '' });
          Util.UI.toast('解绑成功');
          setTimeout(function () {
            wx.switchTab({
              url: '../index/index',
            })
          }, 1000)
        } else if (res.data.error == Config.ERR.ER) {
          Util.UI.loading(1000, res.data.data);
        }
      });
  }

});

